import config from '@/config'
import storage from '@/utils/storage'
import constant from '@/utils/constant'
import { isHttp, isEmpty } from "@/utils/validate"
import { login, logout, getInfo } from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth'
import defAva from '@/static/images/profile.jpg'

const baseUrl = config.baseUrl

const user = {
  state: {
    token: getToken(),
    id: storage.get(constant.id),
    name: storage.get(constant.name),
    avatar: storage.get(constant.avatar),
    roles: storage.get(constant.roles),
    permissions: storage.get(constant.permissions)
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_ID: (state, id) => {
      state.id = id
      storage.set(constant.id, id)
    },
    SET_NAME: (state, name) => {
      state.name = name
      storage.set(constant.name, name)
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
      storage.set(constant.avatar, avatar)
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
      storage.set(constant.roles, roles)
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions
      storage.set(constant.permissions, permissions)
    }
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      const username = userInfo.username.trim()
      const password = userInfo.password
      const code = userInfo.code
      const uuid = userInfo.uuid
  // 准备调用登录接口，参数已从 userInfo 中获取
      return new Promise((resolve, reject) => {
        login(username, password, code, uuid).then(res => {
          
          // request.js 已经返回了 res.data，所以这里 res 就是后端的 data 对象
          // 后端返回格式：{code: 0, data: {userId, accessToken, ...}}
          // request.js 的 resolve(res.data) 让我们直接拿到 data 对象
          const token = res.accessToken || res.token
          
          
          if (!token) {
            console.error('❌ 未获取到 token，完整响应:', JSON.stringify(res))
            reject('登录失败：未获取到token')
            return
          }
          
          setToken(token)
          commit('SET_TOKEN', token)
          // Token 已保存
          resolve()
        }).catch(error => {
          console.error('❌ 登录接口错误:', error)
          reject(error)
        })
      })
    },

    // 获取用户信息
    GetInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        getInfo().then(res => {
          if (!res || res === null) {
            reject('用户信息为空，请检查账号状态')
            return
          }
          const user = res.user || res
          let avatar = (user && user.avatar) ? user.avatar : ''
          if (avatar && !isHttp(avatar)) {
            avatar = baseUrl + avatar
          } else if (!avatar || isEmpty(avatar)) {
            avatar = defAva
          }
          const userid = (isEmpty(user) || isEmpty(user.userId)) ? "" : user.userId
          const username = (user && (user.nickName || user.nickname || user.nick_name || user.userName || user.user_name || user.username || user.loginName)) || ''
          if (res.roles && res.roles.length > 0) {
            commit('SET_ROLES', res.roles)
            commit('SET_PERMISSIONS', res.permissions)
          } else {
            commit('SET_ROLES', ['ROLE_DEFAULT'])
          }
          commit('SET_ID', userid)
          commit('SET_NAME', username)
          commit('SET_AVATAR', avatar)
          // 已写入 store: id, name, avatar
          resolve(res)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 退出系统
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          commit('SET_PERMISSIONS', [])
          removeToken()
          storage.clean()
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    }
  }
}

export default user
